<?php
namespace app\libs;

include_once VENDOR_PATH . '/ezyang/htmlpurifier/library/HTMLPurifier.auto.php';

class HTMLPurification {
    public static $ALLOW = 'img[src],strong,b,p[data-role],hr,h1,h2,br,div,a[href|target],blockquote,video[src|poster|controls],mark[data-id]';

    /**
     * 过滤白名单以外的 HTML 标签
     *
     * @param $text
     * @return string
     */
    public function pure(& $text) {
        $config = \HTMLPurifier_Config::createDefault();
        
        $config->set('Core.Encoding', 'utf-8');
        $config->set('Core.RemoveInvalidImg', false);
        $config->set('Attr.DefaultImageAlt', '');
        $config->set('HTML.Allowed', static::$ALLOW);
        // 不要在链接上加 rel="noreferrer"
        $config->set('HTML.TargetNoreferrer', false);
        // 不要在链接上加 rel="noopener"
        $config->set('HTML.TargetNoopener', false);
        //$config->set('Cache.DefinitionImpl', null);
                
        $def = $config->getHTMLDefinition(true);
        $def->addElement('video', 'Inline', 'Inline', null, ['src' => 'Text', 'poster' => 'Text', 'controls' => 'Text']);
        $def->addElement('mark', 'Inline', 'Inline', null, ['data-id' => 'Text']);
        $def->addAttribute('a', 'target', 'Enum#_blank');
        $def->addAttribute('p', 'data-role', 'Text');

        $purifier = new \HTMLPurifier($config);
        
        return $purifier->purify($text);
    }
}
